package com.liuwei.msmall.order.listener;

import com.liuwei.msmall.common.dto.mq.SeckillOrderTo;
import com.liuwei.msmall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @Classname OrderSeckillListener
 * @Date 2020/10/26 17:07
 * @Created by 刘
 */
@Slf4j
@RabbitListener(queues = {"order.seckill.order.queue"})//标明接收哪些队列的数据
@Service
public class OrderSeckillListener {

    @Autowired
    private OrderService orderService;

    //监听秒杀服务创建的订单
    @RabbitHandler
    public void handleSeckillOrder(Message message, SeckillOrderTo seckillOrderTo, Channel channel) throws IOException {

        System.out.println("处理秒杀服务的订单："+seckillOrderTo.toString());
        try {
            orderService.createSeckillOrder(seckillOrderTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            log.error("创建订单失败：{}",e);
            //出现异常直接将消息重新入队
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }

    }
}
